﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using Things.Common;
using Things.ThingsWeb;
using com.yeepay.icc;
using System.Text;

namespace Things.Web.PersonalCenter
{
    public partial class Default : System.Web.UI.Page
    {
        protected Things.BLL.GoodsOrders goBLL = new BLL.GoodsOrders();

        protected string p1_MerId = Buy.GetMerId();

        protected string p2_Order;
        protected string p3_Amt;
        protected string p4_Cur;
        protected string p5_Pid;
        protected string p6_Pcat;

        protected string p7_Pdesc;
        protected string p8_Url;
        protected string p9_SAF;
        protected string pa_MP;
        protected string pd_FrpId;

        protected string pr_NeedResponse;
        protected string hmac;

        protected string reqURL_onLine = Buy.GetBuyUrl();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                CheckBuyer();
                BindData();
            }
        }

        public void CheckBuyer()
        {
            if (Session[ConstantString.SessionCurrentBuyerAccount] == null)
            {
                Session[ConstantString.SessionSourceURL] = Context.Request.Url;
                Response.Redirect(ConstantString.LoginPageURL);
            }
        }

        protected void BindData()
        {
            Things.Model.Buyer buyer = Session[ConstantString.SessionCurrentBuyerAccount] as Things.Model.Buyer;
            if (buyer !=null)
            {
                DataSet ds = goBLL.GetListByBuyerAccount(buyer.Account);
                if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                {
                    gridView.Visible = true;
                    Label1.Visible = false;
                    gridView.DataSource = ds;
                    gridView.DataBind();
                }
                else
                {
                    gridView.Visible = false;
                    Label1.Visible = true;
                }
            }
        }

        protected void gridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gridView.PageIndex = e.NewPageIndex;
            BindData();
        }

        protected void gridView_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                string strGUID = gridView.DataKeys[e.Row.DataItemIndex - gridView.PageIndex*gridView.PageSize].Value.ToString();
                Guid guid = Guid.Empty;
                if (Guid.TryParse(strGUID, out guid) == true)
                {
                    DataList dataList1 = (DataList)e.Row.FindControl("DataList1");
                    if (dataList1 != null)
                    {
                        DataSet ds = goBLL.GetGoodsListByGoodsOrderID(guid);
                        dataList1.DataSource = ds;
                        dataList1.DataBind();

                        // 评论

                    }
                    Things.Model.GoodsOrders goModel = goBLL.GetModel(guid);
                    if (goModel != null)
                    {
                        
                        // 付款
                        LinkButton lbtPay = e.Row.FindControl("lbtPay") as LinkButton;
                        if (lbtPay != null)
                        {
                            lbtPay.Visible = goModel.Status == ConstantString.GoodsOrderSatus.未付款.ToString();
                            lbtPay.CommandArgument = guid.ToString();
                        }

                        // 取消订单
                        LinkButton lbtCancel = e.Row.FindControl("lbtCancel") as LinkButton;
                        if (lbtCancel != null)
                        {
                            lbtCancel.Visible = goModel.Status == ConstantString.GoodsOrderSatus.未付款.ToString();
                            lbtCancel.CommandArgument = guid.ToString();
                        }

                        // 查看订单
                        LinkButton lbtView = e.Row.FindControl("lbtView") as LinkButton;
                        if (lbtView != null)
                        {
                            //lbtView.Visible = goModel.Status == ConstantString.GoodsOrderSatus.已付款.ToString();
                            //lbtView.PostBackUrl = "~/GoodsOrders/ViewOrder.aspx?ID=" + guid.ToString();
                        }

                        // 确认收货
                        LinkButton lbtShouHuo = e.Row.FindControl("lbtShouHuo") as LinkButton;
                        if (lbtShouHuo != null)
                        {
                            lbtShouHuo.Visible = goModel.Status == ConstantString.GoodsOrderSatus.已发货.ToString();
                            lbtShouHuo.CommandArgument = guid.ToString();
                        }

                        // 评论
                        LinkButton lbtComment = e.Row.FindControl("lbtComment") as LinkButton;
                        if (lbtComment != null)
                        {
                            //lbtComment.Visible = goModel.Status == ConstantString.GoodsOrderSatus.已发货.ToString();
                            // link
                        }
                    }
                }

            }
        }

        protected void gridView_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            
        }

        protected void gridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            
        }

        protected void gridView_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            string strGUID = e.CommandArgument.ToString();
            Guid guid = Guid.Empty;
            if (Guid.TryParse(strGUID, out guid) == true)
            {
                Things.Model.GoodsOrders goModel = goBLL.GetModel(guid);

                string command = e.CommandName;
                switch (command)
                {
                    case "PayOrder":
                        // 付款
                        if (goModel != null)
                        {
                            string url = HttpContext.Current.Request.Url.AbsoluteUri;
                            // http://localhost:1302/TESTERS/Default6.aspx

                            string path = HttpContext.Current.Request.Url.AbsolutePath;
                            // /TESTERS/Default6.aspx

                            string hostURL = url.Remove(url.IndexOf(path), path.Length);

                            List<string> infos = GetGoodsInfo(goModel);

                            Pay( goModel.GoodsOrderNumber.ToString(), goModel.TotalPrice.ToString(), infos[0], infos[1], "", hostURL + "/GoodsOrders/Callback.aspx", "");
                           
                        }
                        break;
                    case "CancelOrder":
                        if (goModel != null)
                        {
                            goModel.Status = ConstantString.GoodsOrderSatus.交易关闭.ToString();
                            goBLL.Update(goModel);

                            BindData();
                        }
                        break;
                    case "QueRenShouHuo":
                        if (goModel != null)
                        {
                            goModel.Status = ConstantString.GoodsOrderSatus.交易成功.ToString();
                            goBLL.Update(goModel);

                            BindData();
                        }
                        break;
                    default:
                        break;
                }
            }            
        }

        protected string GetReceiverName(object obj)
        {
            string result = string.Empty;

            try
            {
                string temp = obj.ToString();
                result = temp.Split(new string[] { ", " }, StringSplitOptions.None)[0];
            }
            catch
            {
            }

            return result;
        }

        // 付款
        protected void Pay(string goodsOrderNumber, string totalPrice, string goodsNames, string goodsCategory,
                                string goodsDescription, string returnURL, string goodsExtentInfomation)
        {
            string temp = string.Empty;

            //1
            //p2_Order	商户平台订单号
            //若不为""，提交的订单号必须在自身账户交易中唯一;为""时，易宝支付会自动生成随机的商户订单号.
            p2_Order = goodsOrderNumber;
            //p3_Amt	交易金额  精确两位小数，最小值为0.01,为持卡人实际要支付的金额.                 
            p3_Amt = totalPrice;
            //交易币种,固定值"CNY".
            p4_Cur = "CNY";
            //商品名称
            //用于支付时显示在易宝支付网关左侧的订单产品信息.
            p5_Pid = goodsNames;
            //商品种类
            p6_Pcat = goodsCategory;
            //2
            //商品描述
            p7_Pdesc = goodsDescription;
            //商户接收支付成功数据的地址,支付成功后易宝支付会向该地址发送两次成功通知.
            p8_Url = returnURL;
            //送货地址
            //为“1”: 需要用户将送货地址留在易宝支付系统;为“0”: 不需要，默认为 ”0”.
            p9_SAF = "0";
            //商户扩展信息
            //商户可以任意填写1K 的字符串,支付成功时将原样返回.	
            pa_MP = goodsExtentInfomation;
            //银行编码
            //默认为""，到易宝支付网关.若不需显示易宝支付的页面，直接跳转到各银行、神州行支付、骏网一卡通等支付页面，该字段可依照附录:银行列表设置参数值.
            pd_FrpId = "";
            //3
            //应答机制
            //默认为"1": 需要应答机制;
            pr_NeedResponse = "1";

            temp = Buy.CreateBuyHmac(p2_Order, p3_Amt, p4_Cur, p5_Pid, p6_Pcat, p7_Pdesc, p8_Url, p9_SAF, pa_MP, pd_FrpId, pr_NeedResponse);

            string[] infos = temp.Split(new string[] { ";#" }, StringSplitOptions.None);

            Session[Common.ConstantString.SessionPayForm] = infos[1];
            Response.Redirect("~/GoodsOrders/Pay.aspx");
        }

        protected void ibtSearch_Click(object sender, ImageClickEventArgs e)
        {
            string date = ddlDate.SelectedValue;
            string key = textfield2.Value.Trim();

            DateTime filterDate = new DateTime(2010, 1, 1);
            switch (date)
            {
                case "0":
                    break;
                case "1":
                    filterDate = DateTime.Now.AddDays(-7);
                    break;
                case "2":
                    filterDate = DateTime.Now.AddDays(-30);
                    break;
                case "3":
                    filterDate = DateTime.Now.AddDays(-90);
                    break;
                default:
                    break;
            }
            Things.Model.Buyer buyer = Session[ConstantString.SessionCurrentBuyerAccount] as Things.Model.Buyer;
            if (buyer != null)
            {
                Things.BLL.GoodsOrders goBLL = new BLL.GoodsOrders();
                DataSet ds = goBLL.GetList(buyer.Account, filterDate, key);

                gridView.DataSource = ds;
                gridView.DataBind();
            }
        }

        protected List<string> GetGoodsInfo(Things.Model.GoodsOrders goModel)
        {
            List<string> infos = new List<string>();

            StringBuilder sbGoodsNames = new StringBuilder();
            StringBuilder sbGoodsTypes = new StringBuilder();

            if (goModel != null)
            {
                Things.BLL.GoodsOrders goBLL = new BLL.GoodsOrders();
                DataSet ds = goBLL.GetGoodsListByGoodsOrderID(goModel.GoodsOrdersID);
                DataRowCollection rows = ds.Tables[0].Rows;
                foreach (DataRow row in rows)
                {
                    sbGoodsNames.Append(row["GoodsName"].ToString());
                    sbGoodsNames.Append(";");

                    sbGoodsTypes.Append(row["GoodsCategoryName"].ToString());
                    sbGoodsTypes.Append(";");
                }
            }

            infos.Add(PageUtility.GetLimitedStringWithDotted(sbGoodsNames.ToString(), 20));
            infos.Add(PageUtility.GetLimitedStringWithDotted(sbGoodsTypes.ToString(), 20));

            return infos;
        }

    }
}